using MediatR;
using S.O.Api.Write.Application.Command.Medical;
using S.O.Domain.Medical;
using S.O.ErrorCode;
using S.O.Interstructrue.Base;

namespace S.O.Api.Write.Application.Handler.Medical
{
    /// <summary>
    /// 创建医疗卡办理处理器
    /// 负责处理医疗卡的办理业务逻辑
    /// </summary>
    public class CreateMedicalCardHandler : IRequestHandler<CreateMedicalCardCommand, APIResult<string>>
    {
        /// <summary>
        /// 医疗卡信息仓储
        /// </summary>
        private readonly IBaseRepository<MedicalCardModel> _medicalCardRepository;
        
        /// <summary>
        /// 患者信息仓储
        /// </summary>
        private readonly IBaseRepository<PatientModel> _patientRepository;
        
        /// <summary>
        /// 日志记录器
        /// </summary>
        private readonly ILogger<CreateMedicalCardHandler> _logger;

        /// <summary>
        /// 构造函数，通过依赖注入初始化所需服务
        /// </summary>
        /// <param name="medicalCardRepository">医疗卡信息仓储</param>
        /// <param name="patientRepository">患者信息仓储</param>
        /// <param name="logger">日志记录器</param>
        public CreateMedicalCardHandler(
            IBaseRepository<MedicalCardModel> medicalCardRepository,
            IBaseRepository<PatientModel> patientRepository,
            ILogger<CreateMedicalCardHandler> logger)
        {
            _medicalCardRepository = medicalCardRepository;
            _patientRepository = patientRepository;
            _logger = logger;
        }

        /// <summary>
        /// 处理创建医疗卡办理命令
        /// </summary>
        /// <param name="request">医疗卡办理命令</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>包含医疗卡号的API结果</returns>
        public async Task<APIResult<string>> Handle(CreateMedicalCardCommand request, CancellationToken cancellationToken)
        {
            try
            {
                _logger.LogInformation($"开始办理医疗卡，患者ID: {request.PatientId}, 姓名: {request.PatientName}, 办卡类型: {request.CardType}");
                
                // 验证输入参数
                var validationResult = ValidateRequest(request);
                if (!validationResult.IsValid)
                {
                    return new APIResult<string>
                    {
                        Code = APIEnums.Error,
                        Msg = validationResult.ErrorMessage
                    };
                }
                
                // 验证患者是否存在，如果不存在则创建新患者
                var patient = _patientRepository.GetALL()
                    .FirstOrDefault(p => p.Id == request.PatientId && !p.IsDeleted);
                    
                if (patient == null)
                {
                    // 检查是否已存在相同身份证的患者
                    var existingPatient = _patientRepository.GetALL()
                        .FirstOrDefault(p => p.IdCard == request.IdCard && !p.IsDeleted);
                        
                    if (existingPatient != null)
                    {
                        // 如果存在相同身份证的患者，使用该患者记录
                        patient = existingPatient;
                        request.PatientId = patient.Id; // 更新请求中的患者ID
                        _logger.LogInformation($"找到现有患者记录，患者ID: {patient.Id}, 姓名: {patient.PatientName}");
                    }
                    else
                    {
                        // 创建新的患者记录
                        var newPatient = new PatientModel
                        {
                            PatientName = request.PatientName,
                            IdCard = request.IdCard,
                            Phone = request.Phone,
                            IsEnable = true,
                            CreateTime = DateTime.Now,
                            CreateUser = request.Operator
                        };
                        
                        var patientResult = _patientRepository.Create(newPatient);
                        if (patientResult > 0)
                        {
                            patient = newPatient;
                            request.PatientId = patient.Id; // 更新请求中的患者ID
                            _logger.LogInformation($"创建新患者记录成功，患者ID: {patient.Id}, 姓名: {patient.PatientName}");
                        }
                        else
                        {
                            return new APIResult<string>
                            {
                                Code = APIEnums.Error,
                                Msg = "创建患者信息失败"
                            };
                        }
                    }
                }
                else
                {
                    // 验证患者身份信息是否匹配
                    if (patient.PatientName != request.PatientName || patient.IdCard != request.IdCard)
                    {
                        return new APIResult<string>
                        {
                            Code = APIEnums.Error,
                            Msg = "患者身份信息不匹配"
                        };
                    }
                }
                
                // 如果是补办或换卡，验证原卡号
                if ((request.CardType == "补办" || request.CardType == "换卡" || request.CardType == "挂失补办") 
                    && string.IsNullOrWhiteSpace(request.OriginalCardNo))
                {
                    return new APIResult<string>
                    {
                        Code = APIEnums.Error,
                        Msg = "原卡号不存在或已失效"
                    };
                }
                
                // 如果提供了原卡号，验证原卡是否存在
                if (!string.IsNullOrWhiteSpace(request.OriginalCardNo))
                {
                    var originalCard = _medicalCardRepository.GetALL()
                        .FirstOrDefault(c => c.CardNo == request.OriginalCardNo && c.PatientId == request.PatientId && !c.IsDeleted);
                        
                    if (originalCard == null)
                    {
                        return new APIResult<string>
                        {
                            Code = APIEnums.Error,
                            Msg = "原卡号不属于该患者"
                        };
                    }
                    
                    // 如果是挂失补办，将原卡状态设置为已挂失
                    if (request.CardType == "挂失补办")
                    {
                        originalCard.CardStatus = "已挂失";
                        _medicalCardRepository.Update(originalCard);
                    }
                    // 如果是换卡，将原卡状态设置为已注销
                    else if (request.CardType == "换卡")
                    {
                        originalCard.CardStatus = "已注销";
                        _medicalCardRepository.Update(originalCard);
                    }
                }
                
                // 生成新的医疗卡号
                var newCardNo = GenerateCardNo();
                
                // 确保卡号唯一性
                while (_medicalCardRepository.GetALL().Any(c => c.CardNo == newCardNo))
                {
                    newCardNo = GenerateCardNo();
                }
                
                // 创建医疗卡记录
                var medicalCard = new MedicalCardModel
                {
                    CardNo = newCardNo,
                    PatientId = request.PatientId,
                    PatientName = request.PatientName,
                    IdCard = request.IdCard,
                    Phone = request.Phone,
                    CardType = request.CardType,
                    CardFee = request.CardFee,
                    CardStatus = "已办理",
                    IssueDate = DateTime.Now,
                    ActivateDate = DateTime.Now,
                    ExpiryDate = DateTime.Now.AddYears(5), // 默认5年有效期
                    Operator = request.Operator,
                    IssueLocation = request.IssueLocation,
                    Remarks = request.Remarks ?? $"{request.CardType}医疗卡",
                    IsFirstTime = request.IsFirstTime,
                    OriginalCardNo = request.OriginalCardNo,
                    IsEnable = true,
                    CreateTime = DateTime.Now,
                    CreateUser = request.Operator
                };
                
                // 保存到数据库
                var result = _medicalCardRepository.Create(medicalCard);
                
                if (result > 0)
                {
                    _logger.LogInformation($"医疗卡办理成功，卡号: {newCardNo}, 患者: {request.PatientName}, 类型: {request.CardType}");
                    return new APIResult<string>
                    {
                        Code = APIEnums.Success,
                        Data = newCardNo,
                        Msg = $"{request.CardType}成功，医疗卡号: {newCardNo}"
                    };
                }
                else
                {
                    _logger.LogError($"医疗卡办理失败，数据库保存失败，患者: {request.PatientName}");
                    return new APIResult<string>
                    {
                        Code = APIEnums.Error,
                        Msg = "医疗卡办理失败，请稍后重试"
                    };
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"医疗卡办理时发生异常，患者: {request.PatientName}");
                return new APIResult<string>
                {
                    Code = APIEnums.Error,
                    Msg = "医疗卡办理失败，系统异常"
                };
            }
        }
        
        /// <summary>
        /// 验证请求参数
        /// </summary>
        /// <param name="request">请求参数</param>
        /// <returns>验证结果</returns>
        private (bool IsValid, string ErrorMessage) ValidateRequest(CreateMedicalCardCommand request)
        {
            if (request.PatientId <= 0)
            {
                return (false, "患者ID不能为空");
            }
            
            if (string.IsNullOrWhiteSpace(request.PatientName))
            {
                return (false, "患者姓名不能为空");
            }
            
            if (string.IsNullOrWhiteSpace(request.IdCard))
            {
                return (false, "身份证号不能为空");
            }
            
            if (!IsValidIdCard(request.IdCard))
            {
                return (false, "身份证号格式不正确");
            }
            
            if (string.IsNullOrWhiteSpace(request.Phone))
            {
                return (false, "联系电话不能为空");
            }
            
            if (!IsValidPhone(request.Phone))
            {
                return (false, "联系电话格式不正确");
            }
            
            var validCardTypes = new[] { "新办", "补办", "换卡", "挂失补办" };
            if (!validCardTypes.Contains(request.CardType))
            {
                return (false, "办卡类型不正确，支持的类型：新办、补办、换卡、挂失补办");
            }
            
            if (request.CardFee < 0)
            {
                return (false, "办卡费用不能为负数");
            }
            
            return (true, string.Empty);
        }
        
        /// <summary>
        /// 验证身份证号格式
        /// </summary>
        /// <param name="idCard">身份证号</param>
        /// <returns>是否有效</returns>
        private bool IsValidIdCard(string idCard)
        {
            if (string.IsNullOrWhiteSpace(idCard))
                return false;
                
            // 简单的身份证号格式验证（15位或18位数字）
            return (idCard.Length == 15 || idCard.Length == 18) && 
                   idCard.All(c => char.IsDigit(c) || (idCard.Length == 18 && idCard[17] == 'X'));
        }
        
        /// <summary>
        /// 验证手机号格式
        /// </summary>
        /// <param name="phone">手机号</param>
        /// <returns>是否有效</returns>
        private bool IsValidPhone(string phone)
        {
            if (string.IsNullOrWhiteSpace(phone))
                return false;
                
            // 简单的手机号格式验证（11位数字，以1开头）
            return phone.Length == 11 && phone.StartsWith("1") && phone.All(char.IsDigit);
        }
        
        /// <summary>
        /// 生成医疗卡号
        /// 格式：年月日 + 4位随机数
        /// </summary>
        /// <returns>医疗卡号</returns>
        private string GenerateCardNo()
        {
            var dateStr = DateTime.Now.ToString("yyyyMMdd");
            var random = new Random().Next(1000, 9999);
            return $"{dateStr}{random}";
        }
    }
}